<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref, defineEmits, markRaw } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getSizeList, doSizeDelete,doSizeSortable } from '#/api/sizeGroup';
import { Button, message, Popconfirm } from 'ant-design-vue';
import type { VbenFormProps } from '#/adapter/form'
import SizeForm from './sizeForm.vue';
import TwoFields from '#/views/backend/modules/two-fields.vue';

import { AntPlusOutlined } from '@vben/icons';

const emit = defineEmits(['fetch-data']);
const data = ref<any>();
const title = ref('尺码管理');
const sizeGroupId = ref<number>(0);
const sizeGroupName = ref<string>('');

// 获取选中的行数据
const selectedRows = ref<any>([]);

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'weigh',
  order: 'desc',
};

const gridOptions: VxeTableGridOptions = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  height: '600px',
  rowConfig: { useKey: true, keyField: 'id', isHover: true,drag: true },
  columnConfig: { useKey: true },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues();
        const queryParams = {
          page: page.currentPage,
          limit: page.pageSize,
          params: {
            id: sizeGroupId.value,
          },
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        };

        const { list, total } = await getSizeList(queryParams);

        return {
          items: list || [],
          total: total || 0,
        };
      },
    },
    sort: true,
  },
  columns: [
    { type: 'checkbox', width: 60, align: 'center', fixed: 'left' },
    {
      field: 'id',
      width: 70,
      title: 'ID',
      sortable: true,
      align: 'center',
    },
    {
      field: 'sizeGroup.name',
      minWidth: 160,
      title: '尺码组',
      sortable: false,
      align: 'center',
    },
    {
      field: 'name',
      width: 160,
      title: '尺码名称',
      sortable: false,
      align: 'center',
    },
    {
      field: 'description',
      width: 200,
      title: '尺码描述',
      sortable: false,
      align: 'center',
    },
    {
      field: 'weigh',
      width: 100,
      title: '权重',
      sortable: true,
      align: 'center',
      dragSort: true
    },
    {
      field: 'create_time',
      width: 180,
      title: '创建时间',
      sortable: true,
      align: 'center',
    },
    {
      field: 'update_time',
      width: 180,
      title: '修改时间',
      sortable: true,
      align: 'center',
    },
    {
      field: 'operation',
      title: '操作',
      width: 190,
      align: 'center',
      fixed: 'right',
      slots: {
        default: 'operation',
      },
    },
  ],
  pagerConfig: {
    currentPage: 1,
    pageSize: 30,
    pageSizes: [30, 50, 100, 200, 300],
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'reviced_record_list',
  customConfig: {
    storage: true,
  },
  
};

/**
 * Grid 事件监听器
 */
const gridEventsHandler = {
  rowDragend: ({ newRow, oldRow, dragPos }: any) => {
    // console.log(`拖拽完成，被拖拽行：${oldRow.name} 目标行：${newRow.name} 目标位置：${dragPos}`)
    handleSortable(oldRow.id, newRow.id);
  },
  checkboxChange: () => {
    selectedRows.value = gridApi.grid.getCheckboxRecords();
  },
  checkboxAll: () => {
    selectedRows.value = gridApi.grid.getCheckboxRecords();
  },
};
// 表单配置
const formOptions: VbenFormProps ={
    wrapperClass: 'grid-cols-5',
    schema: [
      {
        component: markRaw(TwoFields),
        fieldName: 'id',
        disabledOnChangeListener: false,
        label: 'ID',
        operator: 'RANGE',
        valueToString: true,
        componentProps: {
          allowClear: true,
          placeholder: '范围筛选',
        },
      },
      {
        component: 'Input',
        fieldName: 'sizeGroup*name',
        label: '尺码组',
        operator: 'LIKE',
        componentProps: {
          placeholder: '模糊查询',
          allowClear: true,
        },
      },
      {
        component: 'Input',
        fieldName: 'name',
        label: '尺码名称',
        operator: 'LIKE',
        componentProps: {
          placeholder: '模糊查询',
          allowClear: true,
        },
      },
      {
        component: 'Input',
        fieldName: 'description',
        label: '尺码描述',
        operator: 'LIKE',
        componentProps: {
          placeholder: '模糊查询',
          allowClear: true,
        },
      },
      {
        component: markRaw(TwoFields),
        fieldName: 'weigh',
        disabledOnChangeListener: false,
        label: '权重',
        operator: 'RANGE',
        valueToString: true,
        componentProps: {
          allowClear: true,
          placeholder: '范围筛选',
        },
      },
      {
        component: 'RangePicker',
        fieldName: 'create_time',
        label: '创建时间',
        operator: 'RANGE',
        valueToString: true,
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          placeholder: ['开始日期', '结束日期'],
        },
      },
      {
        component: 'RangePicker',
        fieldName: 'update_time',
        label: '修改时间',
        operator: 'RANGE',
        valueToString: true,
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          placeholder: ['开始日期', '结束日期'],
        },
      },
    ],
    showCollapseButton: false,
    collapsed: false,
    submitOnEnter: true,
  }

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions:formOptions,
  gridOptions,
  gridEvents: gridEventsHandler,
});

/**
 * 尺码排序
 */
const handleSortable = async (oldRowId: number, newRowId: number) => {
  await doSizeSortable({ id: oldRowId, targetId: newRowId });
  // message.success('排序成功');
  fetchData();
};

/**
 * 新增尺码
 */
const handleCreate = () => {
  sizeFormModalApi.setData({ info: { pid: sizeGroupId.value }, sizeGroupId: sizeGroupId.value }).open();
};

/**
 * 编辑尺码
 */
const handleEdit = (row: any) => {
  sizeFormModalApi.setData({ info: row, sizeGroupId: sizeGroupId.value }).open();
};

/**
 * 删除尺码
 */
const handleDelete = async (row: any) => {
  try {
    await doSizeDelete({ ids: [row.id] });
    message.success('删除成功');
    fetchData();
  } catch (error) {
    console.error('删除失败:', error);
  }
};


/**
 * 刷新表格
 */
const fetchData = async () => {
  gridApi.reload();
};

const [SizeFormModal, sizeFormModalApi] = useVbenModal({
  connectedComponent: SizeForm,
  onClosed: () => {
    fetchData();
  },
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-4/5',
  destroyOnClose: true,
  onOpenChange: (isOpen: boolean) => {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>()
      sizeGroupId.value = data.value?.sizeGroupId || 0
      sizeGroupName.value = data.value?.sizeGroupName || ''
      title.value = `尺码管理 - ${sizeGroupName.value}`
    }
  },
  onCancel: () => {
    modalApi.close()
  },
  onConfirm: () => {
    modalApi.close()
  },
})
</script>

<template>
  <Modal :title="title">
    <div class="size-modal-content">
      <Grid>
        <template  #toolbar-actions>
          <Button type="primary" @click="handleCreate">
            <AntPlusOutlined />
            新增尺码
          </Button>
        </template>

        <template #operation="{ row }">
          <Button class="mr-2" type="link" size="small" @click="handleEdit(row)">编辑</Button>
          <Popconfirm title="确定要删除吗？" @confirm="handleDelete(row)">
            <Button type="link" size="small" danger>删除</Button>
          </Popconfirm>
        </template>
      </Grid>
      <SizeFormModal @fetch-data="fetchData" />
    </div>
  </Modal>
</template>

<style scoped>
.size-modal-content {
  min-height: 400px;
}
</style>

